package com.jie.demo.mockmvc;

import com.jie.demo.controller.DemoController2;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * 独立测试方式
 * 指定要测试的类
 * 经测试，由于没有初始化spring容器，所有依赖注入将失效
 * 此种模式，适合单独开发的功能，没哟调用其他模块接口，或者自己mock其他接口返回值
 * 优点是测试速度快
 *
 * 步骤
 * 1、首先自己创建相应的控制器，注入相应的依赖

 2、通过MockMvcBuilders.standaloneSetup模拟一个Mvc测试环境，通过build得到一个MockMvc

 3、MockMvc
 */
public class SpringMockMvcInit01 {
    private MockMvc mockMvc;
    @Before
    public void setUp(){
        // 指定模拟 DemoController ，进行测试
        DemoController2 demoController = new DemoController2();
        mockMvc = MockMvcBuilders.standaloneSetup(demoController).build();
    }
    @Test
    public void test() throws Exception {
        String content="22";
        MvcResult result =mockMvc.perform(MockMvcRequestBuilders.post("/test2/query").
                accept(MediaType.APPLICATION_JSON_UTF8).content(content))
                .andExpect(status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
        Assert.assertNotNull(result.getResponse().getContentAsString());
    }
}
